﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;

namespace WowGuildSite.Armory
{
    public class ArmoryReputationCollection : IEnumerable<ArmoryReputation>
    {
        private ArmoryCharacter             character;
        private Hashtable                   reputations = new Hashtable();

        public ArmoryReputation             this[ReputationKey key]
        {
            get 
            {
                ParseReputations();
                return reputations[key] as ArmoryReputation; 
            }
        }

        public IEnumerator<ArmoryReputation> GetEnumerator()
        {
            ParseReputations();

            foreach (ArmoryReputation r in reputations.Values)
            {
                yield return r;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IList<ArmoryReputation>      GetByCategory(ReputationCategory category)
        {
            List<ArmoryReputation> result = new List<ArmoryReputation>();

            foreach (ArmoryReputation r in this)
            {
                if (r.Category == category)
                {
                    result.Add(r);
                }
            }
            return result;
        }

        public bool                         IsAtLeast(ReputationKey key, ReputationStatus status)
        {
            ArmoryReputation reputation = this[key];
            if (reputation != null)
            {
                return reputation.IsAtLeast(status);
            }
            return false;
        }

        public bool                         IsHeroicKeyAvailabe(ReputationKey key)
        {
            ArmoryReputation reputation = this[key];
            if (reputation != null)
            {
                return reputation.IsHeroicKeyAvailable;
            }
            return false;
        }

        private void                        ParseReputations()
        {
            if (reputations.Count > 0)
            {
                return;
            }

            IList<XmlElement> reputationElements = character.SheetDocument.GetElements("/page/characterInfo/reputationTab/factionCategory/faction");

            foreach (XmlElement reputationElement in reputationElements)
            {
                ArmoryReputation reputation = ArmoryReputation.FromElement(reputationElement);
                reputations.Add(reputation.Key, reputation);
            }
        }

        internal ArmoryReputationCollection( ArmoryCharacter character )
        {
            if (character == null)
            {
                throw new ArgumentNullException("character");
            }

            this.character = character;
        }
    }
}
